<script lang="ts" setup>
  import { onMounted, ref, watch } from 'vue';

  const props = defineProps<{
    modelValue?: string;
    options: string[];
  }>();

  const emit = defineEmits(['update:modelValue']);

  const list = ref<
    {
      value: string;
    }[]
  >([]);

  const addItem = () => {
    list.value.push({
      value: '',
    });
  };

  const removeItem = (index: number) => {
    list.value.splice(index, 1);
  };

  watch([list.value], () => {
    emit(
      'update:modelValue',
      JSON.stringify(list.value.map((i) => i.value).filter((i) => i.length > 0))
    );
  });

  onMounted(() => {
    if (props.modelValue) {
      const ary = JSON.parse(props.modelValue) as string[];
      list.value = ary.map((i) => {
        return {
          value: i,
        };
      });
    }
  });
</script>

<template>
  <div class="multi-input">
    <div v-for="(item, index) in list" :key="index" class="multi-input-item">
      <a-select
        v-model="item.value"
        placeholder="请选择或输入"
        allow-create
        :options="options"
      />

      <a-button shape="circle" @click="removeItem(index)">
        <template #icon>
          <icon-minus />
        </template>
      </a-button>
    </div>
    <div class="multi-input-add" @click="addItem">
      <icon-plus />
      添加
    </div>
  </div>
</template>

<style lang="less" scoped>
  .multi-input {
    flex: 1;
    &-item {
      margin-bottom: 12px;
      display: flex;
      &:deep(.arco-btn) {
        margin-left: 12px;
      }
    }
    &-add {
      border-radius: 3px;
      cursor: pointer;
      line-height: 32px;
      display: flex;
      align-items: center;
      justify-content: center;
      border: 1px dashed var(--color-border-2);
      color: var(--color-text-3);
      &:hover {
        color: rgb(var(--primary-6));
        border-color: rgb(var(--primary-6));
      }
    }
  }
</style>
